/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package AutoCalculate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 
 * 
 *
 * @author apple
 */
public class autoCal extends javax.swing.JFrame {

    public List<String> list;
    String answer;
    int allExercise;
    int corr=0;
    int i=0;
    

    public autoCal(String input) {
        char[] ins = input.toCharArray();
        list = new ArrayList<String>();
        String str = "";
        
        

        for (int i = 0; i < ins.length; i++) {
            //为负数的情况,如-1+2,  2*(-1+2)
            if (ins[i] == '-' && ins[i + 1] >= '0' && ins[i + 1] <= '9'
                    && (i == 0 || ins[i - 1] == '(')) {
                str += ins[i];
                continue;
            }
            //为()-()的情况
            if (ins[i] == '-' && ins[i + 1] == '(' && (i == 0 || ins[i - 1] != ')')) {
                list.add("0");
                list.add("-");
                list.add("1");
                list.add("*");
                continue;
            }
            if (!checkFuhao(ins[i])) {
                str += ins[i];
                if (i == ins.length - 1) {
                    list.add(str);
                }
            } else {
                if (!"".equals(str)) {
                    list.add(str);
                    str = "";
                }
                list.add(ins[i] + "");
            }
            //判断2()的情况
            if (i > 0 && ins[i] == '(' && ins[i - 1] >= '0' && ins[i - 1] <= '9') {
                list.add(list.size() - 1, "*");
            }
        }

    }
   

    /**
     * 主方法,通过迭代的形式,输入经过分解后的集合
     *
     * @param list
     * @return 运算结果
     */
    private String yunsuan(List<String> list) {
        try {
            int zuo = haveZuoKuoHao(list);
            if (zuo != -1) {
                int you = lastYouKuohao(list, zuo);
                List<String> l = removeKuohao(list, zuo, you);
                addKuohao(list, yunsuan(l), zuo);
                yunsuan(list);
            }
            int chengchu = haveChengChu(list);
            if (chengchu != -1) {
                chengchuYunsuan(list, chengchu);
            } else {
                jiajianYunsuan(list);
            }
            if (list.size() == 1) {
                return list.get(0);
            }
        } catch (Exception e) {
            System.out.println("error");
            System.exit(0);
        }
        return yunsuan(list);
    }

    /**
     * 去括号后替换原括号为括号运算后的值
     *
     * @param list
     * @param yunsuan
     * @param zuo
     */
    private void addKuohao(List<String> list, String yunsuan, int zuo) {
        list.add(zuo, yunsuan);

    }

    /**
     * 当最后只有+-符号后,进行运算
     *
     * @param list
     */
    private void jiajianYunsuan(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals("+")) {
                double last = Double.parseDouble(list.remove(i + 1));
                list.remove(i);
                double first = Double.parseDouble(list.get(i - 1));
                list.set(i - 1, last + first + "");
                i--;
            }
            if (list.get(i).equals("-")) {
                double last = Double.parseDouble(list.remove(i + 1));
                list.remove(i);
                double first = Double.parseDouble(list.get(i - 1));
                list.set(i - 1, first - last + "");
                i--;
            }
        }

    }

    /**
     * 进行乘除运算
     *
     * @param list
     * @param chengchu
     */
    private void chengchuYunsuan(List<String> list, int chengchu) {
        double last = Double.parseDouble(list.remove(chengchu + 1));
        String fuhao = list.remove(chengchu);
        double first = Double.parseDouble(list.get(chengchu - 1));
        if (fuhao.equals("*")) {
            list.set(chengchu - 1, first * last + "");
        }
        if (fuhao.equals("/")) {
            list.set(chengchu - 1, first / last + "");
        }

    }

    /**
     * 判断算式中是否有乘除
     *
     * @param list
     * @return 乘除符号的位置
     */
    private int haveChengChu(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals("*") || list.get(i).equals("/")) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 将括号移除,并把括号内的算式重新记为一个算式
     *
     * @param list
     * @param zuo
     * @param you
     * @return 括号内的算式
     */
    private List<String> removeKuohao(List<String> list, int zuo, int you) {
        List<String> l = new ArrayList<String>();
        list.remove(you);
        list.remove(zuo);
        for (int i = zuo; i <= you - 2; i++) {
            l.add(list.remove(i));
            i--;
            you--;
        }
        return l;
    }

    /**
     * 如果有左括号
     *
     * @param list
     * @return 左括号的位置
     */
    private int haveZuoKuoHao(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals("(")) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 某个左括号所对应的右括号
     *
     * @param list
     * @param zuo
     * @return 这个右括号的位置
     */
    private int lastYouKuohao(List<String> list, int zuo) {
        int zuoIndex = 1;
        int youIndex = 0;
        for (int i = zuo + 1; i < list.size(); i++) {
            if (list.get(i).equals("(")) {
                zuoIndex++;
            }
            if (list.get(i).equals(")")) {
                youIndex++;
            }
            if (zuoIndex == youIndex) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 判断是否为符号
     *
     * @param a
     * @return
     */
    private boolean checkFuhao(char a) {
        if (a == '+' || a == '-' || a == '*' || a == '/' || a == '('
                || a == ')') {
            return true;
        }
        return false;
    }

    private void output(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i));
        }
        System.out.println();
    }

    public void cre() throws Exception {
        Scanner in = new Scanner(System.in);
        int[] num = new int[4];
        int[] a = new int[4];
        char[] operator = new char[4];
        operator[0] = '+';
        operator[1] = '-';
        operator[2] = '*';
        operator[3] = '/';
        for (int i = 0; i < 4; i++) {
            num[i] = (int) (Math.random() * 10);
            Random rand = new Random();
            if (i != 1) {
                a[i] = rand.nextInt(4);
            } else {
                a[i] = rand.nextInt(2);
            }
        }
        String rstring = num[0] + "" + operator[a[0]] + "" + num[1] + "" + operator[a[1]] + "" + num[2] + "" + operator[a[2]] + "" + num[3];

        ExerciseText.setText(rstring);

  

    }

    /**
     * Creates new form CreAndCal
     */
    public autoCal() {
        initComponents();
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSeparator1 = new javax.swing.JSeparator();
        timeText = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        answerText = new javax.swing.JTextField();
        ExerciseText = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        ResultText = new javax.swing.JTextField();
        creButten = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("所用时间：");

        jButton1.setText("确认");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("结束");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel2.setText("题目：");

        jLabel3.setText("请输入答案：");

        jLabel5.setText("结果：");

        creButten.setText("生成");
        creButten.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                creButtenActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(52, 52, 52)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(timeText, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(105, 105, 105))
            .addGroup(layout.createSequentialGroup()
                .addGap(169, 169, 169)
                .addComponent(jButton3)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addGap(33, 33, 33))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(ResultText, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(187, 187, 187))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(ExerciseText, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(43, 43, 43)
                                .addComponent(creButten, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(answerText)
                                .addGap(43, 43, 43)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(63, 63, 63))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(timeText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(ExerciseText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(creButten))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(answerText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ResultText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                .addComponent(jButton3)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
         String s1 =answerText.getText();
        autoCal s = new autoCal(ExerciseText.getText());
        List<String> list = s.list;
       // System.out.println("正确答案:" + s.yunsuan(list));
        if (s1.equalsIgnoreCase(s.yunsuan(list))) {
            //System.out.println("正确!");
            ResultText.setText("正确！");
            corr += 1;
            //System.out.println(corr);
        } else {
            ResultText.setText("错误！");
        }
        
      
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void creButtenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_creButtenActionPerformed
        try {
            // TODO add your handling code here:
            cre();
            allExercise+=1;
            //System.out.println(allExercise);
            
        } catch (Exception ex) {
            Logger.getLogger(autoCal.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_creButtenActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        new confirm().setVisible(true);
        FileOutputStream fop = null;
  File file;
  String allE = ""+allExercise+" ";
  String corre=""+corr+" ";
  try {
  
   file = new File("C:\\result.txt");
   fop = new FileOutputStream(file);
  
   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }
  
   // get the content in bytes
   byte[] contentInBytes1 = allE.getBytes();
   byte[] contentInBytes2 = corre.getBytes();
   fop.write(contentInBytes1);
   fop.write(contentInBytes2);
   fop.flush();
   fop.close();
  
   System.out.println("Done");
  
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fop != null) {
     fop.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
        
        
        
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(autoCal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(autoCal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(autoCal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(autoCal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new autoCal().setVisible(true);
                
                 i+=1;
                //System.out.println(i); 
                timeText.setText(i+"");
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField ExerciseText;
    private javax.swing.JTextField ResultText;
    private javax.swing.JTextField answerText;
    private javax.swing.JButton creButten;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField timeText;
    // End of variables declaration//GEN-END:variables
}
